package shuimin.weixin.security;

import pond.common.HTTP;
import pond.common.S;
import pond.common.struc.Cache;
import pond.web.EndToEndException;
import shuimin.weixin.Config;
import shuimin.weixin.Constant;

import java.io.IOException;
import java.util.Map;

/**
 * Created by sky on 16/5/18.
 */
public class AccessToken {

    private static final Cache<String, Object> ACCESS_TOKEN_POOL = Cache.lruCache(1000);

    public static String getAccessToken() {
        Object _expires_time = ACCESS_TOKEN_POOL.get("expires_time");
        if (_expires_time != null) {
            Long expires_time = (Long) _expires_time;
            if (expires_time < S.now()) {
                _getAccessToken();
            }
        } else _getAccessToken();

        return (String) ACCESS_TOKEN_POOL.get("access_token");

    }

    private static void _getAccessToken() {
        try {
            String url = Constant.QY_API_URL_PREFIX + Constant.TOKEN_URL + "corpid=" + Config.getCorpId() + "&corpsecret=" + Config.getSecret();
            HTTP.get(url, resp -> {


                    Map<String, Object> map = shuimin.weixin.HTTP.parseRespToJson(resp);

                    if (map == null) {
                        throw new RuntimeException("微信通讯失败");
                    }
                    Object errmsg = map.get("errmsg");
                    if (errmsg != null) {
                        throw new EndToEndException(500, (String) errmsg);
                    }
                    ACCESS_TOKEN_POOL.put("access_token", map.get("access_token"));
                    Integer expires_in = (Integer) map.get("expires_in");

                    ACCESS_TOKEN_POOL.put("expires_time", expires_in * 1000 + S.now() - 1000);
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
